package ace.cmp.spring.util.core;

import ace.cmp.core.exception.BusinessException;
import ace.cmp.core.model.R;
import java.util.function.Supplier;
import lombok.extern.slf4j.Slf4j;

/**
 * @author caspar
 * @date 2023/10/26 9:04
 */
@Slf4j
public final class LogUtils {

  public static <T> R<T> log(String exceptionMsg, Supplier<R<T>> supplier) {
    try {
      R<T> result = supplier.get();
      return result;
    } catch (BusinessException ex) {
      return R.fail(ex.getCode(), ex.getMessage());
    } catch (Exception ex) {
      log.error(exceptionMsg, ex);
      return R.fail(exceptionMsg);
    }
  }

  public static <T> T logThrowExceptionOrDirectThrowBusinessException(String exMessage, Supplier<T> supplier) {
    try {
      return supplier.get();
    } catch (BusinessException ex) {
      String msg = String.format("%s,原因:[%s] %s", exMessage, ex.getCode(), ex.getMessage());
      throw new BusinessException(msg, ex);
    } catch (Exception ex) {
      String msg = String.format("%s,原因:%s", exMessage, ex.getMessage());
      log.error(msg, ex);
      throw new BusinessException(msg, ex);
    }
  }
}
